﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Web.Utility;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using System.Web.UI.HtmlControls;
using BySoft.Server.Business.UserCode;

namespace BySoft.Web.Site.StockManage
{
    public partial class PurchaseAdd : AuthBasePage
    {
        #region 属性定义
        private string m_strsequenceName = "BsPurchase" + DateTime.Now.ToString("yyyyMMdd");
        private string m_strTbl = "BS_Purchase";
        private string m_strMainKey = "BillID";

        private DataTable DtPurchaseData
        {
            get
            {
                if (null == Session["PurchaseData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["PurchaseData"];
                }
            }
            set
            {
                Session["PurchaseData"] = value;
            }
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BillDetailID");//0
            dt.Columns.Add("OrderNum");//1
            dt.Columns.Add("RquisitionDetailID");//2
            dt.Columns.Add("RquisitionID");//3
            dt.Columns.Add("WorkOrderNo");//4
            dt.Columns.Add("MaterialID");//5
            dt.Columns.Add("MaterialName");//6
            dt.Columns.Add("Specifications");//7
            dt.Columns.Add("Unit");//8
            dt.Columns.Add("RquisitionNums");//需求数量
            dt.Columns.Add("ResNum");//剩余数量
            dt.Columns.Add("Nums");//11
            dt.Columns.Add("MMNumber");//11
            dt.Columns.Add("SingleMMNumber");//11
            dt.Columns.Add("Price");//12
            dt.Columns.Add("Amount");//13
            dt.Columns.Add("ExpectDate");//14
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            DtPurchaseData = null;
            SetControlAttr(new BsPurchaseEntity(), tBase);
            lblBillID.Text = ClsComm.GetBillCode(m_strTbl, m_strMainKey, "PO" + DateTime.Now.ToString("yyMMdd"), 3);
            cpBillDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
            UIHelper.BindEmptyGridView(grdResult, CreateDT());
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            txtSupplierID.Attributes.Add("readonly", "true");
            txtSupplierName.Attributes.Add("readonly", "true");
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

        private void AddPro()
        {
            DtPurchaseData = GetAddPro(DtPurchaseData).Copy();
        }
        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblBillDetailID = gvr.FindControl("lblBillDetailID") as Label;
                Label lblOrderNum = gvr.FindControl("lblOrderNum") as Label;
                Label lblRquisitionDetailID = gvr.FindControl("lblRquisitionDetailID") as Label;
                Label lblRquisitionID = gvr.FindControl("lblRquisitionID") as Label;
                Label lblWorkOrderNo = gvr.FindControl("lblWorkOrderNo") as Label;
                Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                Label lblUnit = gvr.FindControl("lblUnit") as Label;
                Label lblRquisitionNums = gvr.FindControl("lblRquisitionNums") as Label;
                Label lblResNum = gvr.FindControl("lblResNum") as Label;
                Label lblSingleMMNumber = gvr.FindControl("lblSingleMMNumber") as Label;
                TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
                TextBox txtMMNumber = gvr.FindControl("txtMMNumber") as TextBox;
                TextBox txtPrice = gvr.FindControl("txtPrice") as TextBox;
                TextBox txtAmount = gvr.FindControl("txtAmount") as TextBox;
                HtmlInputText cpExpectDate = gvr.FindControl("cpExpectDate") as HtmlInputText;

                string MaterialID = CommonMethod.GetString(lblMaterialID.Text);


                DataRow[] drs = dtTemp.Select("MaterialID='" + MaterialID + "'");
                if (drs.Length > 0)
                {
                    drs[0]["BillDetailID"] = GetGridViewString(lblBillDetailID);
                    drs[0]["OrderNum"] = GetGridViewString(lblOrderNum);
                    drs[0]["RquisitionDetailID"] = GetGridViewString(lblRquisitionDetailID);
                    drs[0]["RquisitionID"] = GetGridViewString(lblRquisitionID);
                    drs[0]["WorkOrderNo"] = GetGridViewString(lblWorkOrderNo);
                    drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                    drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                    drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                    drs[0]["Unit"] = GetGridViewString(lblUnit);
                    drs[0]["RquisitionNums"] = GetGridViewString(lblRquisitionNums);
                    drs[0]["ResNum"] = GetGridViewString(lblResNum);
                    drs[0]["Nums"] = GetGridViewString(txtNums);
                    drs[0]["SingleMMNumber"] = GetGridViewString(lblSingleMMNumber);
                    drs[0]["MMNumber"] = GetGridViewString(txtMMNumber);
                    drs[0]["Price"] = GetGridViewString(txtPrice);
                    drs[0]["Amount"] = GetGridViewString(txtAmount);
                    drs[0]["ExpectDate"] = GetGridViewString(cpExpectDate);
                }
            }
            return dtTemp;
        }

        private void BindData()
        {
            DataView dv = new DataView(DtPurchaseData);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel1, "iframeAutoFit();");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            AddPro();
            UIHelper.RunScript(this.Page, "importNewRow('0');");
        }

        protected void btnAddh_Click(object sender, EventArgs e)
        {
            AddPro();
            BindData();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            BsPurchaseEntity entity = new BsPurchaseEntity();
            entity.BillID = GetString(lblBillID);
            entity.BillDate = GetDateTime(cpBillDate);
            entity.SupplierID = GetString(txtSupplierID);
            entity.Status = "1";
            entity.CreateUserID = CurrentUser.UserID;
            entity.CreateUserName = CurrentUser.UserName;
            entity.CreateDate = DateTime.Now;
            entity.ModifyUserID = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;


            //int index = 1;
            //foreach (GridViewRow gvr in grdResult.Rows)
            //{
            //    Label lblBillDetailID = gvr.FindControl("lblBillDetailID") as Label;
            //    Label lblRquisitionDetailID = gvr.FindControl("lblRquisitionDetailID") as Label;
            //    Label lblResNum = gvr.FindControl("lblResNum") as Label;
            //    TextBox txtNums = gvr.FindControl("txtNums") as TextBox;

            //    if (string.IsNullOrEmpty(txtNums.Text.Trim()))
            //    {
            //        UIHelper.AlertMessage(this.UpdatePanel1, string.Format("第{0}行，请输入数量！", index));
            //        return;
            //    }

            //    decimal dResNum = BsPurchaseBusiness.SelectResNum(lblRquisitionDetailID.Text, lblBillID.Text);
            //    if (CommonMethod.ConvertToDecimal(txtNums.Text.Trim()) > dResNum)
            //    {
            //        UIHelper.AlertMessage(this.UpdatePanel1, string.Format("第{0}行，数量不能大于剩余数量{1}", index, dResNum));
            //        lblResNum.Text = dResNum.ToString();
            //        return;
            //    }
            //    index++;
            //}

            BsPurchaseBusiness.SaveOrUpdate(entity, DtPurchaseData, "Save");
            base.LogAction(BaseEnum.ActionType.Add, entity.BillID, true, null, new EntityBase[] { entity });
            DtPurchaseData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../StockManage/PurchaseList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "del":
                    AddPro();
                    DataTable dt = DtPurchaseData.Copy();
                    DataRow[] dr = dt.Select("MaterialID='" + strCode.Trim() + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    DtPurchaseData = dt.Copy();
                    BindData();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion

                TextBox txtAmount = e.Row.FindControl("txtAmount") as TextBox;
                txtAmount.Attributes.Add("readonly", "true");
                string strcpExpectDate = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["ExpectDate"].ToString().Trim();
                HtmlInputText cpExpectDate = e.Row.FindControl("cpExpectDate") as HtmlInputText;
                if (cpExpectDate != null)
                {
                    cpExpectDate.Value = CommonMethod.ConvertToDate(strcpExpectDate);
                }
            }
        }
        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            AddPro();
            if (DtPurchaseData.Rows.Count < 1)
            {
                UIHelper.AlertMessage(this.UpdatePanel1, "请添加明细！");
                return false;
            }
            string strMention = "";

            string strOriMainKey = UIHelper.GetQueryStringValue("id").Trim();
            if (!string.IsNullOrEmpty(strOriMainKey))
            {
                if (lblBillID.Text != strOriMainKey)
                {
                    if (ClsComm.CheckExist("BS_Purchase", "BillID", lblBillID.Text.Trim(), true))
                    {
                        strMention = "材料采购单编号已经存在！<br />";
                    }
                }
            }
            else
            {
                if (ClsComm.CheckExist("BS_Purchase", "BillID", lblBillID.Text.Trim(), true))
                {
                    strMention = "材料采购单编号已经存在！<br />";
                }
            }

            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }
        #endregion

        protected void btnRquisition_Click(object sender, EventArgs e)
        {
            AddPro();
            UIHelper.RunScript(this.Page, "importNewRow('1');");
        }
    }
}

